<?php
class Forum_View
{
    /**
     * Script file name to execute
     *
     * @var string
     */
    private $_file = null;
    
    /**
     * @var array
     * @access private
     */
    private $_vars = array();
    
    public function __construct($config = array())
    {
        
    }
    
    /**
     * Processes a view script and returns the output.
     *
     * @param string $name The script script name to process.
     * @return string The script output.
     */
    public function render($name)
    {
        $this->_file = $this->_script($name);

        ob_start();
        include $this->_file;

        return ob_get_clean();
    }
    
    /**
     * Returns full path to script file
     * 
     * @param string $name Path to view script inside template dir
     * @return string|throw an Exception
     */
    protected function _script($name)
    {
        $dir_template = BP . DS . 'app' . DS . 'design' . DS . Forum::getConfig()->design->template . DS . 'template' . DS;
        $dir_layout   = BP . DS . 'app' . DS . 'design' . DS . Forum::getConfig()->design->template . DS . 'layout' . DS;
        
        if (is_readable($dir_template . $name)) {
            return $dir_template . $name;
        }
        
        if (is_readable($dir_layout . $name)) {
            return $dir_layout . $name;
        }
        
        $message = "script '$name' not found in path (" . $dir_template . " and " . $dir_layout . ")";
        throw new Exception($message);
    }
    
    /** 
     * Retrieve the variable from vars array
     * 
     * @param $name String
     * @return mixed
     */
    public function __get($name)
    {
        if (isset($this->_vars[$name])) {
            return $this->_vars[$name];
        }
        
        return Forum_Controller_Front::getInstance()->getResponse()->getBody($name);
    }
    
    /**
     * Assign value to the vars with name key
     *
     * @param string $index
     * @param mixed $value
     * @return void
     */
    public function __set($name, $value)
    {
        $this->_vars[$name] = $value;
    }
    
    /**
     * Magic call for helpers
     * 
     * @param string $method
     * @param array $attrs
     * @return
     */    
    public function __call($method, $attrs)
    {
        return call_user_func(array('Forum_Helper_' . ucfirst($method), 'getInstance'));
    }
    
    /**
     * Assign value to the vars with name key
     * 
     * @param $name String
     * @param $value Mixed
     * @return void
     */
    public function assign($name, $value)
    {
        $this->_vars[$name] = $value;
    }
    
    public function escape($var)
    {
        return htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
    }
}